package com.yami.shop.service;


import com.yami.shop.bean.model.RecommendItem;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
/**
 * @author DELL
 */
@Repository
@RequiredArgsConstructor
public class SimpleRecommender {
    private final JdbcTemplate jdbc;

    private static final String RECOMMEND_SQL = """
        WITH user_preference AS (
            SELECT 
                prod_id,
                SUM(
                    CASE behavior_type
                        WHEN 'PURCHASE' THEN 5 * EXP(-TIMESTAMPDIFF(DAY, timestamp, NOW())/30) 
                        WHEN 'FAVORITE' THEN 3 * EXP(-TIMESTAMPDIFF(DAY, timestamp, NOW())/60)
                        WHEN 'CART' THEN 2 * EXP(-TIMESTAMPDIFF(DAY, timestamp, NOW())/45)
                        WHEN 'VIEW' THEN 1 * EXP(-TIMESTAMPDIFF(DAY, timestamp, NOW())/15)
                    END
                ) AS score
            FROM user_behavior 
            WHERE user_id = ?
            GROUP BY prod_id
        ),
        hot_products AS (
            SELECT 
                prod_id,
                COUNT(*) * 0.8 + SUM(
                    CASE behavior_type 
                        WHEN 'PURCHASE' THEN 2 
                        ELSE 1 
                    END
                ) * 0.2 AS hot_score
            FROM user_behavior
            GROUP BY prod_id
            ORDER BY hot_score DESC
            LIMIT 50
        )
        SELECT 
            COALESCE(up.prod_id, hp.prod_id) AS recommend_id,
            COALESCE(up.score, 0) * 0.7 + hp.hot_score * 0.3 AS final_score
        FROM user_preference up
        RIGHT JOIN hot_products hp ON up.prod_id = hp.prod_id
        WHERE NOT EXISTS (
            SELECT 1 
            FROM user_behavior 
            WHERE user_id = ? 
                AND behavior_type = 'PURCHASE' 
                AND prod_id = hp.prod_id
        )
        ORDER BY final_score DESC
        LIMIT 10
        """;

    public List<RecommendItem> recommend(String userId) {
        try {
            return jdbc.query(
                RECOMMEND_SQL,
                new Object[]{userId, userId},
                (rs, rowNum) -> new RecommendItem(
                    rs.getLong("recommend_id"),
                    rs.getDouble("final_score")
                )
            );
        } catch (DataAccessException e) {
            // 添加异常处理逻辑，例如记录日志或抛出业务异常
            throw new RecommendationException("Failed to generate recommendations", e);
        }
    }
}

// 建议添加自定义异常类
class RecommendationException extends RuntimeException {
    public RecommendationException(String message, Throwable cause) {
        super(message, cause);
    }
}
